package services;

import java.io.IOException;
import java.net.URL;

import tags.Tag;

import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.contacts.UserDefinedField;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

import datastore.Contact;

public class AddTagToParticipantService {

	private static final String DEFAULT_FEED = "http://www.google.com/m8/feeds/contacts/aliceprivacy@gmail.com/full";
//	private String DEFAULTGROUP_FEED = "http://www.google.com/m8/feeds/groups/testerpromail@gmail.com/full";
	private static final DBService dbService = new DBService();
	
	public String getPassword(String name) throws AuthenticationException{
		Contact contact = dbService.getContact(name);
		return contact.getPassword();
		
	}
	
	public String getTagForParticipant(){
		
		String newTags = ""; 
		
		for(Tag newTag: Tag.values()){
			newTags += newTag + " "; 
		}
		
		newTags = newTags.substring(0, newTags.length() - 1);
		return newTags;
	}
	
	public static void updateContactName(
		    ContactsService myService,  String tags, String emailParticipant,String emailInput)
		    throws ServiceException, IOException {
		
		URL feedUrl = new URL(DEFAULT_FEED);
		ContactFeed resultFeed = myService.getFeed(feedUrl, ContactFeed.class);
		ContactEntry entry = null;
		
		boolean found = false;
		
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			 entry = resultFeed.getEntries().get(i);
			 
			 for (Email email : entry.getEmailAddresses()) {
				 if(email.getAddress().equals(emailParticipant))
					 found = true;
					 break;
			 }
			 
			 if(found){
				 break;
			 }
		}
		
		if(found){
			String [] tagsInArray = tags.split(" ");
			
			for(String tag: tagsInArray){
				UserDefinedField userDefinedField = new UserDefinedField(tag, tag);
				entry.addUserDefinedField(userDefinedField);
			}
			
			URL editUrl = new URL(entry.getEditLink().getHref());
			myService.update(editUrl, entry);
		}
	}
	
	public String getEmailAddresses(ContactsService myService,String emailInput) throws IOException, ServiceException{
		  
		  String emailAddresses = "";
		  
		  System.out.println(DEFAULT_FEED);
		  System.out.println(myService);
		  
		  URL feedUrl = new URL(DEFAULT_FEED);
		  ContactFeed resultFeed = myService.getFeed(feedUrl, ContactFeed.class);
		  
		  for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			 ContactEntry entry = resultFeed.getEntries().get(i);
			 
			 for (Email email : entry.getEmailAddresses()) {
				 //System.out.print(" " + email.getAddress());
				 emailAddresses += email.getAddress() + " ";
			 }
		
		 }
		 
		 return emailAddresses;
		  
	}
	
	
}
